package org.jiuling.netty.test.handler.decoder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.string.StringDecoder;
import org.jiuling.basics.converter.ByteConvert;

import java.util.List;

/**
 * 字节转字符串数组编码器
 * @author 紫灵
 * @date 2025年07月04日 09时56分03秒
 */
public class ByteToStringArrayDecoder extends StringDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
        String split = "(.{2})";
        String newStr = objectToHexStr(msg).toUpperCase().replaceAll(split, "$1 ");
        String[] hexArray = newStr.split(" ");
        out.add(hexArray);
    }

    private static String objectToHexStr(ByteBuf buf) {
        byte[] bytes = new byte[buf.readableBytes()];
        //复制内容到字节数组bytes
        buf.readBytes(bytes);
        //将接收到的数据转为字符串，此字符串就是客户端发送的字符串
        return ByteConvert.byteArrayToHexString(bytes);
    }

}
